/*    Copyright 2010 Tobias Marschall
 *
 *    This file is part of MoSDi.
 *
 *    MoSDi is free software: you can redistribute it and/or modify
 *    it under the terms of the GNU General Public License as published by
 *    the Free Software Foundation, either version 3 of the License, or
 *    (at your option) any later version.
 *
 *    MoSDi is distributed in the hope that it will be useful,
 *    but WITHOUT ANY WARRANTY; without even the implied warranty of
 *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *    GNU General Public License for more details.
 *
 *    You should have received a copy of the GNU General Public License
 *    along with MoSDi.  If not, see <http://www.gnu.org/licenses/>.
 */

package mosdi.matching;

import java.util.Arrays;

public class HorspoolMatcher extends AbstractMatcher {

	private int[] shift;
	
	public HorspoolMatcher(int alphabetSize, int[] pattern) {
		super(alphabetSize, pattern);
		this.pattern = pattern;
		this.shift = computeShiftTable(alphabetSize, pattern);
	}

	public static int[] computeShiftTable(int alphabetSize, int[] pattern) {
		int[] shift = new int[alphabetSize];
		Arrays.fill(shift, pattern.length);
		for (int i=0; i<pattern.length-1; ++i) {
			shift[pattern[i]]=pattern.length-1-i;
		}
		return shift;
	}
	
	@Override
	protected WindowData processWindow(int[] text, int windowEndPos) {
		int cost = 0; 
		int i = 0;
		for (;i<pattern.length; ++i) {
			cost += 1;
			if (text[windowEndPos-i]!=pattern[pattern.length-i-1]) break;
		}
		return new WindowData(i==pattern.length, shift[text[windowEndPos]], cost);
	}
	
}
